<template>
	<view class="feeding-list">
		<view class="top">
			<text class="title">喂食记录</text>
			<text class="handle" @click="showPopup">新增</text>
		</view>

		<!-- 喂食记录列表 -->
		<template v-if="state.dataList.length > 0">
			<view v-for="(feeding, index) in state.dataList" :key="feeding.id" class="feeding" :class="{
        complete: feeding.isComplete,
      }">
				<!-- 				<view class="time-info">
					<text class="tip">{{
            isTodayFeeding(feeding.feedingTime)
              ? "Today"
              : formatDate(new Date(feeding.feedingTime), "MM-dd")
          }}</text>
					<text class="time">{{
            formatDate(new Date(feeding.feedingTime), "hh:mm")
            }}</text>
				</view> -->

				<movable-area class="movable">
					<movable-view class="movable movable-view" :class="{
            'one-btn': feeding.isComplete,
          }" direction="horizontal" inertia damping="20" out-of-bounds :x="feeding.x" @touchstart="touchStart"
						@touchend="touchEnd(index, $event)">
						<view class="info" @click="hideHandle(index)">
							<!-- <image class="avatar" src="@/assets/svgs/plan.svg"></image> -->
							<view class="detail">
								<text class="food">{{ feeding.food }}</text>
								<text class="amount">{{ feeding.feedingTime }}</text>
								<!-- <text class="amount">{{ feeding.amount }} g</text> -->
							</view>
							<view class="time">
								<text class="amount">{{ feeding.amount }}g</text>
							</view>
						</view>
						<view class="handle">
							<view class="btn delete" @click="deleteFeeding(feeding.id)">
								<image class="icon" src="@/assets/svgs/trash-can.svg"></image>
							</view>
<!-- 							<view v-if="!feeding.isComplete" class="btn done" @click="doneFeeding(feeding.id)">
								<image class="icon" src="@/assets/svgs/done.svg"></image>
							</view> -->
						</view>
					</movable-view>
				</movable-area>
			</view>
		</template>
		<!-- 无记录时显示 -->
		<template v-else>
			<view class="empty">空空如也~</view>
		</template>

		<!-- 新增喂食记录 -->
		<MyPopup :show="state.isShowPopup" @hide="hidePopup">
			<view class="popup">
				<view class="title">新增喂食记录</view>
				<view class="form">
					<MyForm :model="state.newFeeding" :rules="rules" ref="myForm">
						<!--            <MyFormItem label="宠物ID" prop="petId">
              <MyInput maxlength="10" @updateModelValue="updateModelValue" :modelValue="state.newFeeding.petId"
                obj="petId" />
            </MyFormItem> -->
						<MyFormItem label="食物" prop="food">
							<MyInput maxlength="30" @updateModelValue="updateModelValue"
								:modelValue="state.newFeeding.food" obj="food" />
						</MyFormItem>
						<MyFormItem label="喂食量(克)" prop="amount">
							<MyInput maxlength="10" type="number" @updateModelValue="updateModelValue"
								:modelValue="state.newFeeding.amount" obj="amount" />
						</MyFormItem>
						<MyFormItem label="喂食时间" prop="feedingTime">
							<MyInput maxlength="20" @updateModelValue="updateModelValue"
								:modelValue="state.newFeeding.feedingTime" obj="feedingTime" />
						</MyFormItem>
						<button class="submit" @click="handleNewFeedingSubmit">完成</button>
					</MyForm>
				</view>
			</view>
		</MyPopup>
		<MyMessage ref="myMessageRef"></MyMessage>
	</view>
</template>

<script>
	// import { Feeding } from "@/types/feeding";
	import {
		formatDate
	} from "@/utils/methods";
	import MyPopup from '@/components/MyPopup/MyPopup.vue'
	import MyForm from '@/components/MyForm/MyForm.vue'
	import MyInput from '@/components/MyInput/MyInput.vue'
	import MyMessage from '@/components/MyMessage/MyMessage.vue'
	import MyFormItem from '@/components/MyFormItem/MyFormItem.vue'
	import {
		mapGetters,
		mapActions
	} from 'vuex';
	import {
		queryFeedingLogs
	} from '@/api/backend'


	export default {
		name: "Feeding",
		props: {
			petId: {
				type: Number, // 根据你的具体数据类型进行调整
				required: true
			},
			data: {
				type: Array,
				default: () => [],
			},
		},
		data() {
			return {
				myForm: null,
				state: {
					dataList: [],
					offset: 10,
					currentTouchX: 0,
					isShowPopup: false,
					newFeeding: {
						petId: "",
						food: "",
						amount: "",
						feedingTime: formatDate(new Date(), "yyyy-MM-dd hh:mm")
					},
					startTime: Date.now(),
					endTime: Date.now() + 1000 * 3600 * 24 * 180,
				},
				rules: {
					// petId: [{
					// 	required: true,
					// 	message: "请输入宠物ID",
					// }, ],
					food: [{
						required: true,
						message: "请输入食物",
					}, ],
					amount: [{
						required: true,
						message: "请输入喂食量",
					}, ],
					feedingTime: [{
						required: true,
						message: "请输入喂食时间",
					}, ],
				},
			};
		},
		components: {
			MyPopup,
			MyForm,
			MyInput,
			MyMessage,
			MyFormItem
		},
		// onLoad(options) {
		// 	console.log("onLoad.....")

		// 	this.getFeedingLogs()
		// },

		// activated(){
		// 	console.log("activated.....")

		// 	this.getFeedingLogs()
		// },

		mounted() {
			console.log("mounted.....")
			this.getFeedingLogs()
		},

		watch: {
			data: {
				handler(newVal) {
					const dataList = newVal.map((item) => {
						return {
							...item,
							x: 0
						};
					});
					const completeds = dataList.filter((item) => item.isComplete);
					const inCompleteds = dataList.filter((item) => !item.isComplete);
					completeds.sort((a, b) => Date.parse(b.feedingTime) - Date.parse(a.feedingTime));
					inCompleteds.sort((a, b) => Date.parse(b.feedingTime) - Date.parse(a.feedingTime));
					this.state.dataList = inCompleteds.concat(completeds);
				},
				immediate: true,
				deep: true,
			},
		},
		methods: {
			...mapActions('pet', ['FeedingAdd']),

			getFeedingLogs() {
				// console.log('queryFeedingLogs this=', this)

				queryFeedingLogs({
					petId: this.petId
				}).then(res => {


					const {
						data
					} = res
					if (data) {
						this.state.dataList = data
					}

					console.log('queryFeedingLogs dataList=', this.state.dataList)
				})
			},
			touchStart(e) {
				const {
					clientX
				} = e.changedTouches[0];
				this.state.currentTouchX = clientX;
			},
			touchEnd(index, e) {
				const {
					clientX
				} = e.changedTouches[0];
				if (this.state.currentTouchX - clientX > this.state.offset) {
					this.state.dataList = this.state.dataList.map((item, i) => {
						if (i !== index) {
							item.x = 0;
						} else {
							item.x = -999;
						}
						return item;
					});
				} else if (clientX - this.state.currentTouchX > this.state.offset) {
					this.state.dataList[index].x = 0;
				}
			},
			hideHandle(index) {
				this.state.dataList[index].x = 0;
			},
			deleteFeeding(id) {
				this.$emit("delete", id);
			},
			doneFeeding(id) {
				this.$emit("done", id);
			},
			showPopup() {
				this.state.newFeeding = {
					// id: this.petId,
					petId: this.petId,
					food: "",
					amount: "",
					feedingTime: formatDate(new Date(), "yyyy-MM-dd hh:mm"),
					isComplete: false,
				};
				this.state.isShowPopup = true;
				// console.log(this.state.newFeeding.id)
			},
			hidePopup() {
				this.state.isShowPopup = false;
			},
			updateModelValue(obj, val) {
				this.state.newFeeding[`${obj}`] = val
			},
			handleNewFeedingSubmit() {
				// console.log(this.state.newFeeding)
				console.log(this)

				// petId, food, amount, feedingTime 是必填项
				if (!this.state.newFeeding.petId || !this.state.newFeeding.food || !this.state.newFeeding.amount || !this
					.state.newFeeding.feedingTime) {
					this.$refs.myMessageRef.show({
						type: 'error',
						message: '请输入必输项！',
					});
					return;
				}
				this.$refs.myForm.validate((valid) => {
					if (valid) {
						// 页面直接触发处理结果 - 第一种
						const param = {
							...this.state.newFeeding,
							"amount": Number(this.state.newFeeding.amount),
							"petId": String(this.state.newFeeding.petId)
						}

						// 这个是触发actions里面的新增 - 第二种 -- 方便统一全局管理
						this.FeedingAdd(param);
						this.hidePopup();
						this.$refs.myMessageRef.show({
							message: "添加成功",
						});


					}
				});
			},
			isTodayFeeding(feedingTime) {
				return new Date(feedingTime).getDate() === new Date().getDate();
			},
		},
	};
</script>

<style lang="less" scoped>
	// 行为相关颜色
	@my-color-primary: #FFA500;
	@my-color-error: #ff4747;

	// 文字相关颜色
	@my-text-color: #303330;
	@my-text-color-grey: rgb(157, 155, 155);

	.feeding-list {
		margin: 0 1.5rem;

		.top {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 0.8rem;

			.title {
				font-weight: bold;
				font-size: 1.1rem;
			}

			.handle {
				color: @my-color-primary;
				font-size: 0.8rem;
			}
		}

		.empty {
			height: 200rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: @my-color-primary;
			opacity: 0.5;
			font-size: 25rpx;
		}

		.feeding {
			display: flex;
			justify-content: space-between;
			margin-bottom: 0.5rem;

			&.complete {
				opacity: 0.5;
			}

			.movable {
				width: 99vw;
				height: 3.8rem;
				overflow: hidden;
				margin-left: 1rem;

				&.one-btn {
					width: 87vw;
				}
			}

			.movable-view {
				display: flex;
			}

			.time-info {
				display: flex;
				flex-direction: column;

				.tip {
					color: @my-text-color-grey;
					font-size: 0.8rem;
				}

				.time {
					font-weight: bold;
				}
			}

			.info {
				height: 3.8rem;
				flex: 1;
				background: #fff;
				border-radius: 1rem;
				margin-right: 0.8rem;
				padding: 0.5rem;
				box-sizing: border-box;
				display: flex;
				align-items: center;

				.avatar {
					height: 2rem;
					width: 2rem;
					border-radius: 0.6rem;
				}

				.detail {
					display: flex;
					flex-direction: column;
					flex: 1;
					margin-left: 0.2rem; /* 减少左边距 */
					margin: 0 0.8rem;

					.food {
						font-weight: bold;
					}

					.amount {
						font-size: 0.7rem;
						color: @my-text-color-grey;
					}
				}

				.time {
					display: flex;
					flex-direction: column;
					align-items: flex-end;

					.number {
						font-weight: bold;
						font-size: 1.2rem;
					}

					.unit {
						color: @my-text-color-grey;
						font-size: 0.6rem;
					}
				}
			}

			.handle {
				display: flex;
				align-items: center;

				.btn {
					width: 2.5rem;
					height: 2.5rem;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 0.8rem;
					margin-right: 0.3rem;

					.icon {
						width: 60%;
						height: 60%;
					}
				}

				.delete {
					background: @my-color-error;
				}

				.done {
					background: @my-color-primary;
				}
			}
		}
	}

	.popup {
		width: 60vw;

		.title {
			font-weight: bold;
			font-size: 1.2rem;
			color: @my-color-primary;
			margin-bottom: 1rem;
		}

		.submit {
			background: @my-color-primary;
			color: #fff;
			font-size: 1rem;
			border-radius: 0.8rem;
			margin-top: 2rem;

			&::after {
				border: none;
			}
		}
	}
</style>